package com.orange.common.binding

import android.text.TextUtils
import android.view.ViewGroup
import androidx.databinding.BindingAdapter
import org.libpag.PAGFile
import org.libpag.PAGText
import org.libpag.PAGView

object PagAdapter {

    @JvmStatic
    @BindingAdapter(
        value = ["pagSrc", "pagText", "pagAutoPlay", "pagRepeatCount"],
        requireAll = false
    )
    fun pagSrc(
        pagView: PAGView,
        pagSrc: String?,
        pagText: String?,
        pagAutoPlay: Boolean = true,
        pagRepeatCount: Int
    ) {
        if (pagView.isPlaying) {
            return
        }
        if (TextUtils.isEmpty(pagSrc)) {
            return
        }
        val pagFile = PAGFile.Load(pagView.context.assets, pagSrc)

        val params = pagView.layoutParams ?: ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        //根据原图尺寸等比修改宽或高
        if (params.width > 0) {
            params.height = (params.width / (pagFile.width() / pagFile.height().toDouble())).toInt()
        } else {
            params.width = (params.height / (pagFile.height() / pagFile.width().toDouble())).toInt()
        }
        if (!TextUtils.isEmpty(pagText)) {
            val textData: PAGText = pagFile.getTextData(0)
            if (textData != null) {
                textData.text = pagText
                pagFile.replaceText(0, textData)
            }
        }
        pagView.layoutParams = params
        pagView.composition = pagFile
        pagView.setRepeatCount(pagRepeatCount)
        if (pagAutoPlay) {
            pagView.play()
        }
    }

}